package com.edocbase.desktop.maildriver;

import java.util.concurrent.LinkedBlockingQueue;

import com.edocbase.biz.diary.entities.IDiary;
import com.edocbase.diary.job.JobManager;
import com.edocbase.diary.job.JobWorker;
import com.edocbase.webdriver.DriverException;
import com.edocbase.webdriver.IWebAccount;

public class DriverWorker {
	private LinkedBlockingQueue<AbstractDriverCommand> cmdQueue = new LinkedBlockingQueue<AbstractDriverCommand>(100);
	private LinkedBlockingQueue<AbstractDriverCommand> sendCmdQueue = new LinkedBlockingQueue<AbstractDriverCommand>(100);
	private CommandJobWorker receiveExecutor;
	private CommandJobWorker sendExecutor;

	private static DriverWorker worker = null;
	public static DriverWorker getWorker(){
		if (worker == null){
			worker = new DriverWorker();
		}
		return worker;
	}
	private DriverWorker() {
		super();
		receiveExecutor = new CommandJobWorker(this, false);
		sendExecutor = new CommandJobWorker(this, true);
	}
	public boolean isReceiving(){
		return receiveExecutor.getState() == JobWorker.JOB_RUNNING_STATU;
	}
	public void receive(IWebAccount account) throws DriverException{
		addCommand(new MailReceiveCommand(account));
	}
	
	public void send(IWebAccount account,IDiary diary) throws DriverException{
		addCommand(new MailSendCommand(account,diary));
	}
	
	public void delete(IWebAccount account,IDiary diary) throws DriverException{
		addCommand(new MailDeleteCommand(account, diary));
	}
	
	
	public void addCommand(AbstractDriverCommand cmd){
		if (cmd instanceof MailSendCommand){
			sendCmdQueue.add(cmd);
			if (!sendExecutor.getState().equals(JobWorker.JOB_RUNNING_STATU)){
				JobManager.getJobManager().execute(sendExecutor);
			}
		}else{
			cmdQueue.add(cmd);
			if (!receiveExecutor.getState().equals(JobWorker.JOB_RUNNING_STATU)){
				JobManager.getJobManager().execute(receiveExecutor);
			}
		}
	}

	AbstractDriverCommand getNextCmd(){
		return cmdQueue.poll();
	}
	
	AbstractDriverCommand getNextSendCmd(){
		return sendCmdQueue.poll();
	}
}
